package com.qf.mq.pubsub;

import com.qf.mq.utils.MqUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DeliverCallback;
import com.rabbitmq.client.Delivery;

import java.io.IOException;

public class ReceiveLogs2 {
    private static final String EXCHANGE_NAME = "logs";

    public static void main(String[] args) throws Exception{

        final Connection connection = MqUtils.getConnection();
        final Channel channel = connection.createChannel();

        channel.exchangeDeclare(EXCHANGE_NAME, "fanout");

        // 声明一个 属性都是默认值，名字是随机字符串的队列，并返回队列的名字
        String queueName = channel.queueDeclare().getQueue();

        /**
         * 绑定队列到交换机
         * 参数1:队列的名字
         * 参数2:交换机的名字
         * 参数3：routingkey，如果是fanout模式的交换机，可以写空串
         */
        channel.queueBind(queueName, EXCHANGE_NAME, "");

        final DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
                final String s = new String(message.getBody(), "utf-8");
                System.out.println("消费者2,消费消息:"+s);
                channel.basicAck(message.getEnvelope().getDeliveryTag(),false);
            }
        };

        channel.basicConsume(queueName, false, deliverCallback, consumerTag -> { });
    }
}
